<template>
  <div class="diary">
    <yk-space v-if="diaryList.length > 0" dir="vertical" size="xl" style="width: 100%;">
      <DiaryItem v-for="item in diaryList" :key="item.id" :diaryData="item" @delete="deleteAndUpdate"
        :searchTerm="props.searchTerm" />
    </yk-space>
    <div v-if="diaryList.length > 0" class="pagination">
      <yk-pagination :total="diaryCount" size="m" @change="changePage"
        :default-page-size="props.pageSize"></yk-pagination>
    </div>
    <Empty v-if="diaryList.length === 0" />
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, getCurrentInstance } from 'vue';
import type { diaryData } from "../../utils/interface";
// import { mkdiary } from '../../mock/data';
import DiaryItem from './diary-item.vue';
import { getDiaryApi, deleteDiaryApi } from "../../api/diary-api";
import { useUserStore } from '../../stores/user';
import { useCode } from "../../hooks/codeHook";
import Empty from '../common/empty.vue';

const userStore = useUserStore();
const { tackleCode } = useCode();
const proxy: any = getCurrentInstance()?.proxy;
const props = defineProps({
  pageSize: {
    type: Number,
    default: 8,
  },
  searchTerm: {
    type: String,
    default: '',
  },
  getRefresh: {
    type: Number,
    default: 0,
  }
})

// const { 
//   deleteDiary,
// } = useDiary();

const request = {
  token: userStore.token,
  pageSize: props.pageSize,
  nowPage: 1,
  searchTerm: props.searchTerm,
  count: true,
}

//获取日记
//日记列表
const diaryList = ref<diaryData[]>([]);
//日记总数
const diaryCount = ref<number>(0);
//获取日记
type getDiaryRequest = {
  token: string;
  pageSize: number;
  nowPage: number;
  searchTerm: string;
  count: boolean;
};

const getDiaryList = (request: getDiaryRequest) => {
  getDiaryApi(request).then((res) => {
    if (tackleCode(res.data.code)) {
      diaryCount.value = res.data.count;
      let data = res.data.data;
      diaryList.value = [...data];
    }
  });
};

// 处理图片字符串数据变成字符串数组
const extractUrls = (imageString: string | undefined) => {
  if (imageString) {
    try {
      const pictureArray = JSON.parse(imageString);
      if (Array.isArray(pictureArray)) {
        return pictureArray.map(item => item.url);
      }
    } catch (e) {
      console.error('解析JSON失败:', e);
      return null;
    }
  }
  return [];
}

//删除日记
const deleteDiary = async (id: number) => {
  try {
    let request = {
      token: userStore.token,
      diaryId: id,
      fileUrl: extractUrls(diaryList.value.find((item) => item.id === id)?.picture),
    };
    const res = await deleteDiaryApi(request);
    if (tackleCode(res.data.code)) {
      diaryList.value = diaryList.value.filter((item) => item.id !== id);
      proxy.$message({ type: "success", message: "删除成功" });
      return true;
    }
    return false;
  } catch (error) {
    proxy.$message({ type: "error", message: "删除失败" });
    return false;
  }
};

// 翻页处理
const changePage = (page: number) => {
  request.nowPage = page;
  getDiaryList(request);
}

//删除日记后，deleteDiary 函数会自动更新本地 diaryList
const deleteAndUpdate = async (id: number) => {
  await deleteDiary(id);
  getDiaryList(request);
}


watch(
  props,
  () => {
    // 当 props.searchTerm 变化时，更新 request.searchTerm 并重新获取日记列表
    request.searchTerm = props.searchTerm;
    getDiaryList(request);
  },
)

onMounted(() => {
  getDiaryList(request);
})
</script>
<style scoped lang="less">
.diary {
  width: 100%;

  .pagination {
    padding: @space-s 0 0 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
  }
}
</style>